import 'dart:math';

import 'package:flutter/material.dart';

class RandomGeoAvatarPainter extends CustomPainter {
  final int seed;
  late final Random random;

  RandomGeoAvatarPainter(this.seed) {
    random = Random(seed);
  }

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()..style = PaintingStyle.fill;

    // 背景圆形（脸部基底）
    paint.color = Color.fromARGB(
      255,
      200 + random.nextInt(56),
      150 + random.nextInt(56),
      150 + random.nextInt(56),
    );
    final center = Offset(size.width / 2, size.height / 2);
    final radius = size.width * 0.45;
    canvas.drawCircle(center, radius, paint);

    // 随机画几个几何形状叠加
    int shapeCount = 3 + random.nextInt(4); // 3-6个形状
    for (int i = 0; i < shapeCount; i++) {
      paint.color = Color.fromARGB(
        255,
        random.nextInt(256),
        random.nextInt(256),
        random.nextInt(256),
      ).withOpacity(0.7);

      double w = size.width * (0.1 + random.nextDouble() * 0.3);
      double h = size.height * (0.1 + random.nextDouble() * 0.3);
      double x = random.nextDouble() * (size.width - w);
      double y = random.nextDouble() * (size.height - h);

      int shapeType = random.nextInt(3);

      switch (shapeType) {
        case 0: // 圆形
          canvas.drawCircle(Offset(x + w / 2, y + h / 2), w / 2, paint);
          break;
        case 1: // 矩形
          canvas.drawRect(Rect.fromLTWH(x, y, w, h), paint);
          break;
        case 2: // 三角形
          final path = Path();
          path.moveTo(x + w / 2, y);
          path.lineTo(x, y + h);
          path.lineTo(x + w, y + h);
          path.close();
          canvas.drawPath(path, paint);
          break;
      }
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

class RandomGeoAvatar extends StatelessWidget {
  final int seed;
  final double size;

  const RandomGeoAvatar({Key? key, required this.seed, this.size = 80})
    : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      size: Size(size, size),
      painter: RandomGeoAvatarPainter(seed),
    );
  }
}
